package com.example.expandablelistview.multimedia;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.example.expandablelistview.R;

public class CameraTest extends Activity {
	MyCameraSurface mSurface;
	Button mShutter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mul_cameratest);
		
		mSurface = (MyCameraSurface) findViewById(R.id.preview);
		
		findViewById(R.id.focus).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mShutter.setEnabled(false);
				mSurface.mCamera.autoFocus(mAutoFocus);
			}
		});
		
		mShutter = (Button) findViewById(R.id.shutter);
		mShutter.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mSurface.mCamera.takePicture(null, null, mPicture);
			}
		});
	}
	
	PictureCallback mPicture = new PictureCallback() {
		public void onPictureTaken(byte[] data, Camera camera) {
			String sd = Environment.getExternalStorageDirectory().getAbsolutePath();
			String path = sd + "/camertest.jpg";
			File file = new File(path);
			try {
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(data);
				fos.flush();
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			//Media DB 갱신
			Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			Uri uri = Uri.parse("file://" + path);
			intent.setData(uri);
			sendBroadcast(intent);
			
			Toast.makeText(CameraTest.this, "사진 저장 완료", Toast.LENGTH_LONG).show();
			mSurface.mCamera.startPreview();
		}
	};
	
	AutoFocusCallback mAutoFocus = new AutoFocusCallback() {
		public void onAutoFocus(boolean success, Camera camera) {
			mShutter.setEnabled(true);
		}
	};
}
